package handler

import (
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	common "listenboos-common"
	"net/http"
	"strings"
	"ucenter-api/internal/logic"
	"ucenter-api/internal/svc"
	"ucenter-api/internal/types"
)

type LoginHandler struct {
	svcCtx *svc.ServiceContext
}

func NewLoginHandler(svcCtx *svc.ServiceContext) *LoginHandler {
	return &LoginHandler{
		svcCtx: svcCtx,
	}
}
func (h *LoginHandler) WechatLogin(w http.ResponseWriter, r *http.Request) {
	var req types.WechatLoginReq
	//if err := r.ParseForm(); err != nil {
	//	httpx.ErrorCtx(r.Context(), w, err)
	//	return
	//}
	//r.PostForm.Get()
	//if err := httpx.Parse(r, &req); err != nil {
	//	httpx.ErrorCtx(r.Context(), w, err)
	//	return
	//}
	path := r.URL.Path
	// 假设路径的格式是/hello/{name}，我们去掉前面的/hello/部分
	code := strings.TrimPrefix(path, "/api/user/")
	newResult := common.NewResult()
	if code == "" {
		httpx.OkJsonCtx(r.Context(), w, newResult.Deal(nil, errors.New("微信登录失败")))
		return
	}
	req.Code = code
	l := logic.NewLoginLogic(r.Context(), h.svcCtx)
	resp, err := l.WechatLogin(&req)
	token := resp.Token
	r.Header.Set("token", token)
	token1 := r.Header.Get("token")
	fmt.Println("-----------")
	fmt.Println(token1)
	result := newResult.Deal(resp, err)
	httpx.OkJsonCtx(r.Context(), w, result)
}

func (h *LoginHandler) GetUserInfo(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(208, "未登录"))
		return
	}
	l := logic.NewLoginLogic(r.Context(), h.svcCtx)
	resp, err := l.GetUserInfo(token)
	if err != nil {
		logx.Errorf("获取用户信息出错")
		httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(208, "获取用户信息出错"))
		return
	}
	result := newResult.Deal(resp, err)
	httpx.OkJsonCtx(r.Context(), w, result)
}

func (h *LoginHandler) UpdateUser(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(208, "未登录"))
		return
	}
	var req types.UpdateUserReq
	err := httpx.ParseJsonBody(r, &req)
	if err != nil {
		logx.Errorf("修改用户信息错误")
		httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(208, "获取用户信息出错"))
		return
	}
	l := logic.NewLoginLogic(r.Context(), h.svcCtx)
	resp, err := l.UpdateUser(token, &req)
	if err != nil {
		logx.Errorf("获取用户信息出错")
		httpx.OkJsonCtx(r.Context(), w, newResult.NoLogin(208, "获取用户信息出错"))
		return
	}
	result := newResult.Deal(resp, err)
	httpx.OkJsonCtx(r.Context(), w, result)
}

//GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
